// src/pages/Topics.js - 话题管理页面

import React, { useState, useEffect } from 'react';

import { useNavigate } from 'react-router-dom';
import {
  Typography, Card, List, Avatar, Button, Space, Tag, Statistic,
  Modal, Form, Input, Select, Row, Col, Tabs, message, Empty,
  Badge, Tooltip
} from 'antd';
import {
  PlusOutlined, UserOutlined, CommentOutlined, EyeOutlined,
  MessageOutlined, TeamOutlined, StarOutlined, ClockCircleOutlined
} from '@ant-design/icons';
import { topics } from '../services';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Topics = () => {
  const navigate = useNavigate();
  const [topicsList, setTopicsList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isCreateModalVisible, setIsCreateModalVisible] = useState(false);
  const [isBanned, setIsBanned] = useState(false);
  const [banMessage, setBanMessage] = useState('');
  const [activeTab, setActiveTab] = useState('all');
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [activeKey, setActiveKey] = useState('all');

  const topicCategories = [
    { value: '资源分享', label: '资源分享', color: '#1890ff' },
    { value: '求助互助', label: '求助互助', color: '#52c41a' },
    { value: '技术交流', label: '技术交流', color: '#722ed1' },
    { value: '影视讨论', label: '影视讨论', color: '#eb2f96' },
    { value: '音乐分享', label: '音乐分享', color: '#fa8c16' },
    { value: '游戏交流', label: '游戏交流', color: '#13c2c2' },
    { value: '生活闲聊', label: '生活闲聊', color: '#f5222d' }
  ];

  useEffect(() => {
    loadTopics();
  }, [activeTab]);

  const loadTopics = async () => {
    try {
      setLoading(true);
      const response = await topics.getTopics();

      if (response.success) {
        let filteredTopics = response.data.topics || [];

        // 根据标签页筛选
        if (activeTab !== 'all') {
          filteredTopics = filteredTopics.filter(topic => topic.category === activeTab);
        }

        // 按创建时间排序，热门话题在前
        filteredTopics.sort((a, b) => {
          const scoreA = (a.memberCount || 0) + (a.postCount || 0) * 2;
          const scoreB = (b.memberCount || 0) + (b.postCount || 0) * 2;
          if (scoreA !== scoreB) return scoreB - scoreA;
          return new Date(b.createTime) - new Date(a.createTime);
        });

        setTopicsList(filteredTopics);
      } else {
        messageApi.error('加载话题失败');
      }
    } catch (error) {
      console.error('加载话题失败:', error);
      messageApi.error('加载话题失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateTopic = async (values) => {
    try {
      const response = await topics.createTopic({
        title: values.name,
        description: values.description,
        category: values.category,
        tags: values.tags ? (Array.isArray(values.tags) ? values.tags.join(',') : values.tags) : '',
        isPublic: values.isPublic !== false
      });

      if (response.code === 403) {
        setIsBanned(true);
        setBanMessage(response.message);
        return;
      }
      if (response.code === 200) {
        messageApi.success('话题创建成功');
        setIsCreateModalVisible(false);
        form.resetFields();
        loadTopics();
      } else {
        messageApi.error(response.message || '创建失败');
      }
    } catch (error) {
      console.error('创建话题失败:', error);
      messageApi.error('创建失败: ' + error.message);
    }
  };

  const handleTopicClick = (topic) => {
    navigate(`/topics/${topic.topicId || topic.id}`);
  };

  const getCategoryColor = (category) => {
    const categoryInfo = topicCategories.find(cat => cat.value === category);
    return categoryInfo ? categoryInfo.color : '#666';
  };

  const formatTime = (timeString) => {
    const time = new Date(timeString);
    const now = new Date();
    const diffInSeconds = Math.floor((now - time) / 1000);

    if (diffInSeconds < 60) return '刚刚';
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
    if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}天前`;

    return time.toLocaleDateString();
  };

  return (
    <div style={{ background: '#f0f2f5', minHeight: 'calc(100vh - 200px)' }}>
      {contextHolder}
      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ margin: 0 }}>
            <TeamOutlined /> 话题广场
          </Title>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            size="large"
            onClick={() => setIsCreateModalVisible(true)}
            style={{
              background: 'linear-gradient(135deg, rgba(102, 126, 234) 0%, rgba(118, 75, 162) 100%)',
              border: 'none',
              color: 'white',
              fontWeight: 'bold'
            }}
          >
            创建话题
          </Button>
        </div>

        <Card style={{ marginBottom: 24 }}>
          <Tabs
            // activeKey={activeTab}
            // onChange={setActiveTab}
            activeKey={activeKey} 
            onChange={setActiveKey}
            size="large"
            style={{ marginBottom: 0 }}
          >
            <TabPane tab="全部话题" key="all" />
            {topicCategories.map(category => (
              <TabPane
                tab={
                  <div style={{ textAlign: 'center' }}>
                    <div>{category.label}</div>
                    {(activeKey === 'all' || activeKey === category.value) && (
                      <div style={{ fontSize: 12, color: '#888' }}>
                        {topicsList.filter(t => t.category === category.value).length} 个话题
                      </div>
                    )}
                  </div>
                }
                key={category.value}
              />
            ))}
          </Tabs>
        </Card>

        <Card>
          <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text type="secondary">
              共 <Text strong>{topicsList.length}</Text> 个话题
            </Text>
          </div>

          <List
            loading={loading}
            dataSource={topicsList}
            locale={{
              emptyText: (
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  description="暂无话题"
                  style={{ marginTop: 32 }}
                >
                  <Button type="primary" onClick={() => setIsCreateModalVisible(true)}>
                    创建第一个话题
                  </Button>
                </Empty>
              )
            }}
            renderItem={topic => (
              <List.Item
                style={{
                  cursor: 'pointer',
                  padding: '16px 0',
                  borderBottom: '1px solid #f0f0f0'
                }}
                onClick={() => handleTopicClick(topic)}
                actions={[
                  <div key="stats" style={{ textAlign: 'center', minWidth: 200 }}>
                    <Row gutter={16}>
                      <Col span={8}>
                        <Statistic
                          title="成员"
                          value={topic.memberCount}
                          prefix={<UserOutlined />}
                          valueStyle={{ fontSize: '14px' }}
                        />
                      </Col>
                      <Col span={8}>
                        <Statistic
                          title="帖子"
                          value={topic.postCount}
                          prefix={<MessageOutlined />}
                          valueStyle={{ fontSize: '14px' }}
                        />
                      </Col>
                      <Col span={8}>
                        <Tooltip title="活跃度">
                          <Statistic
                            title="热度"
                            value={Math.floor((topic.memberCount * 0.3 + topic.postCount * 0.7))}
                            prefix={<StarOutlined />}
                            valueStyle={{ fontSize: '14px', color: '#fa8c16' }}
                          />
                        </Tooltip>
                      </Col>
                    </Row>
                  </div>
                ]}
              >
                <List.Item.Meta
                  avatar={
                    <Avatar
                      size={64}
                      style={{
                        backgroundColor: getCategoryColor(topic.category),
                        fontSize: '24px'
                      }}
                    >
                      {(topic.title || topic.name || '话题').charAt(0)}
                    </Avatar>
                  }
                  title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                      <Tag color={getCategoryColor(topic.category)}>
                        {topic.category}
                      </Tag>
                      <span style={{ fontSize: '18px', fontWeight: 500 }}>
                        {topic.title || topic.name}
                      </span>
                      {topic.isPublic && (
                        <Tag color="green" size="small">公开</Tag>
                      )}
                    </div>
                  }
                  description={
                    <div>
                      <Paragraph
                        style={{
                          marginBottom: 12,
                          color: '#666',
                          display: '-webkit-box',
                          WebkitLineClamp: 2,
                          WebkitBoxOrient: 'vertical',
                          overflow: 'hidden'
                        }}
                      >
                        {topic.description}
                      </Paragraph>

                      <div style={{ marginBottom: 8 }}>
                        <Space wrap>
                          {(typeof topic.tags === 'string' ? topic.tags.split(',') : (topic.tags || [])).map(tag => (
                            <Tag key={tag} size="small">{tag.trim()}</Tag>
                          ))}
                        </Space>
                      </div>

                      <Space size="large">
                        <Text type="secondary">
                          <UserOutlined /> 创建者：{topic.creator}
                        </Text>
                        <Text type="secondary">
                          <ClockCircleOutlined /> 创建于：{formatTime(topic.createTime)}
                        </Text>
                      </Space>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        </Card>

        {/* 封禁提示对话框 */}
        <Modal
          title="账号已被封禁"
          open={isBanned}
          onOk={() => setIsBanned(false)}
          onCancel={() => setIsBanned(false)}
          footer={[
            <Button key="ok" type="primary" onClick={() => setIsBanned(false)}>
              我知道了
            </Button>
          ]}
        >
          <p>{banMessage}</p>
          <p>请稍后再试</p>
        </Modal>

        {/* 创建话题对话框 */}
        <Modal
          title="创建新话题"
          open={isCreateModalVisible}
          onCancel={() => {
            setIsCreateModalVisible(false);
            form.resetFields();
          }}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleCreateTopic}
          >
            <Form.Item
              name="name"
              label="话题名称"
              rules={[
                { required: true, message: '请输入话题名称' },
                { min: 3, message: '话题名称至少3个字符' },
                { max: 50, message: '话题名称不能超过50个字符' }
              ]}
            >
              <Input placeholder="请输入话题名称" size="large" />
            </Form.Item>

            <Form.Item
              name="description"
              label="话题描述"
              rules={[
                { required: true, message: '请输入话题描述' },
                { min: 10, message: '话题描述至少10个字符' },
                { max: 500, message: '话题描述不能超过500个字符' }
              ]}
            >
              <TextArea
                rows={4}
                placeholder="请详细描述这个话题的用途和规则..."
                showCount
                maxLength={500}
              />
            </Form.Item>

            <Form.Item
              name="category"
              label="话题分类"
              rules={[{ required: true, message: '请选择话题分类' }]}
            >
              <Select placeholder="请选择分类" size="large">
                {topicCategories.map(cat => (
                  <Option key={cat.value} value={cat.value}>
                    <Tag color={cat.color} style={{ marginRight: 8 }}>
                      {cat.label}
                    </Tag>
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="tags"
              label="话题标签"
              extra="多个标签用逗号分隔，如：交流,分享,讨论"
            >
              <Input placeholder="请输入话题标签" size="large" />
            </Form.Item>

            <div style={{ textAlign: 'right' }}>
              <Space>
                <Button onClick={() => {
                  setIsCreateModalVisible(false);
                  form.resetFields();
                }}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  创建话题
                </Button>
              </Space>
            </div>
          </Form>
        </Modal>
      </div>
    </div>
  );
};

export default Topics; 